package vinux.web.common.controller;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import net.sf.json.JSONObject;
import vinux.service.common.page.Pagination;
import vinux.service.common.pension.PensionUtils;
import vinux.service.common.statics.LogConstant;
import vinux.service.common.statics.SysConstant;
import vinux.service.common.util.CollectionUtils;
import vinux.service.common.util.StringUtils;
import vinux.service.common.util.SyncUtils;
import vinux.service.common.util.VinuxPostMethod;
import vinux.service.common.util.api.APIUtils;
import vinux.service.common.util.api.CustomeInfoBean;
import vinux.service.common.util.api.FoodInfo;
import vinux.service.common.util.api.OrderInfoBean;
import vinux.service.common.util.api.UserInfoBean;
import vinux.service.core.utils.LoggerUtils;
import vinux.service.core.utils.SystemLogUitls;
import vinux.service.entity.applyinfo.ApplyInfo;
import vinux.service.entity.task.Task;
import vinux.service.entity.userbaseinfo.UserBaseInfo;
import vinux.service.entity.voteputlog.VotePutLog;
import vinux.service.manager.base.PensionManager;
import vinux.service.service.applyinfo.service.ApplyInfoService;
import vinux.service.service.task.service.TaskService;
import vinux.service.service.userbaseinfo.service.UserBaseInfoService;

@Controller
@RequestMapping("initParameter")
public class ParameterController {
	

	
	@Autowired
	private TaskService taskService;
	
	@Autowired
	private DataSource dataSource;
	
	@Autowired
	private ApplyInfoService applyService;
	
	@Autowired
	private UserBaseInfoService userService;
	
	
	/**
	 * 测试同步参数到redis
	 * manager.vinuxagedcare.com/initParameter/synchronization.vhtml  访问
	 * @return
	 */
	
	@RequestMapping("synchronization")
	public ModelAndView synchronization(){
		ModelAndView model = new ModelAndView("demo/parameter_index");
		boolean flag = SyncUtils.sysnParameter();
		String result = "";
		if(flag){
			result = "数据库参数同步到redis缓存成功！！！";
		}
		model.addObject("result", result);
		return model;
	}
	
	
	@RequestMapping("putInApplyInfo2Couci")
	@ResponseBody
	public Map<String,Object> putInApplyUserInfo2Couci(){
		List<ApplyInfo> applyInfoList = CollectionUtils.newArrayList();
		Exception methodMessage = null;
		int log = 0;
		String message = "";
		Map<String,Object> logMap = CollectionUtils.newHashMap();
		try{
			applyInfoList = applyService.selectInApplyUserInfo();
			for(ApplyInfo applyinfo : applyInfoList){
				UserBaseInfo user = userService.selectByUserId(applyinfo.getUserId());
				if(user!=null){
					//向理事会推送 申请养老人员的信息
					Map<String,Object> result = APIUtils.putApplyInfo2Care(user);
					VotePutLog voteResult = new VotePutLog();
					if(StringUtils.isNotBlank(result)){
						if(StringUtils.isNotBlank(result.get("votePutLog"))){
							log++;
							voteResult = (VotePutLog)result.get("votePutLog");
							voteResult.setCreateDate(new Date());
							voteResult.setUpdateTime(new Date());
							logMap.put(""+log, voteResult.toString());
							applyService.putApplyInfo2Couci(voteResult);
						}
					}
					LoggerUtils.debug(getClass(), "申请成功。。。。");
				}
			}
			message = "养老资格审核中数据推送成功";
			logMap.put("message", message);
			logMap.put("totalCount",log);
		}catch (Exception e){
			message = "养老资格审核中数据推送失败";
			logMap.put("message", message);
			methodMessage  = e;
			e.printStackTrace(System.err);
		}finally{
			SystemLogUitls.info(null, logMap.toString(),
					null, getClass(),
					null, methodMessage,
					LogConstant.DATA_DEAL_READ,
					LogConstant.SYSTEM_YANGLAO, "手动推送养老资格审核中的人员信息给基金会", SysConstant.PARAMETERINIT_PUTINAPPLYUSERINFO2COUCI,
					LogConstant.OTHER_LOG_API);
		}
		
		return logMap;
	}
	

	/**
	 * 	测试在redis中通过key来取value值
	 *  manager.vinuxagedcare.com/initParameter/getValue.vhtml  访问
	 * @return
	 */
	
	@RequestMapping("getValue")
	public ModelAndView getValue(){
		ModelAndView model = new ModelAndView("demo/parameter_index");
		String key = "everyday_subsidy_money";
		String value = SyncUtils.getValueByKey(key);
		if(StringUtils.isBlank(value)){
			value = "无对应value值";
		}
		model.addObject("result", key + " : " + value);
		return model;
	}
	
	
	
	/**
	 * 测试养老比例指数算法
	 *  manager.vinuxagedcare.com/initParameter/getPensionRatio.vhtml  访问
	 * @return
	 */
	@RequestMapping("getPensionRatio")
	public ModelAndView getPensionRatio(){
		ModelAndView model = new ModelAndView("demo/parameter_index");
		double bili = PensionManager.getPensionRatio("201193");
		model.addObject("result", bili);
		return model;
	}
	
	
	
	/**
	 * 测试获取社区投票所需的投票人数
	 *  manager.vinuxagedcare.com/initParameter/getVoters.vhtml  访问
	 * @return
	 */
	@RequestMapping("getVoters")
	public ModelAndView getVoters(){
		ModelAndView model = new ModelAndView("demo/parameter_index");
//		int num = PensionManager.getVoterTotals();
//		model.addObject("result", "本社区需要投票的人数为：" + num);
		return model;
	}
	
	
	
	/**
	 * 测试获取社区申请人通过申请所需的投票人数
	 *  manager.vinuxagedcare.com/initParameter/getSuccessVoters.vhtml  访问
	 * @return
	 */
	@RequestMapping("getSuccessVoters")
	public ModelAndView getSuccessVoters(){
		ModelAndView model = new ModelAndView("demo/parameter_index");
//		int num = PensionManager.getSuccessVoterTotals();
//		model.addObject("result", "若通过申请所需本社区需要投票的人数为：" + num);
		return model;
	}
	
	
	/**
	 * 测试购物车接口调用
	 *  manager.vinuxagedcare.com/initParameter/getOrderDetails.vhtml  访问
	 * @return
	 */
	@RequestMapping("getOrderDetails")
	public ModelAndView getOrderDetails(){
		ModelAndView model = new ModelAndView("demo/parameter_index");
		String userId = "281";
		List<OrderInfoBean> data = APIUtils.getOrderDetails(userId,1,10);
		model.addObject("data", data);
		return model;
	}
	
	
	/**
	 * 测试购物车接口调用
	 *  manager.vinuxagedcare.com/initParameter/getByOrderNo.vhtml  访问
	 * @return
	 */
	@RequestMapping("getByOrderNo")
	public ModelAndView getByOrderNo(){
		ModelAndView model = new ModelAndView("demo/parameter_index");
		String userId = "281";
		OrderInfoBean orderInfoBean = APIUtils.getByOrderNo(userId, "201604221756117107");
		model.addObject("orderInfoBean", orderInfoBean);
		return model;
	}
	
	
	/**
	 * 测试基金接口调用
	 *  manager.vinuxagedcare.com/initParameter/geCustomeInfoDetails.vhtml  访问
	 * @return
	 */
	@RequestMapping("geCustomeInfoDetails")
	public ModelAndView geCustomeInfoDetails(){
		ModelAndView model = new ModelAndView("demo/parameter_index");
		String customerid = "18701409089";
		CustomeInfoBean customeInfo = APIUtils.getCustomeInfo(customerid);
		model.addObject("applyrate", "樱桃特权指数为：" + customeInfo.getApplyrate());
		model.addObject("buyAmount", "总购买次数为：" + customeInfo.getCareBuyNum());
		model.addObject("careBuyNum", "总消费金额为：" + customeInfo.getBuyAmount());
		return model;
	}
	
	
	/**
	 * 测试会员接口调用1
	 *  manager.vinuxagedcare.com/initParameter/getUserInfoById.vhtml  访问
	 * @return
	 */
	@RequestMapping("getUserInfoById")
	public ModelAndView getUserInfoById(){
		ModelAndView model = new ModelAndView("demo/parameter_index");
		String userId = "130472";
		UserInfoBean userInfo = APIUtils.getUserInfoById(userId);
		model.addObject("name", "姓名："+userInfo.getName());
		model.addObject("sex", "性别："+userInfo.getSex());
		model.addObject("cartId", "身份证号："+userInfo.getCardId());
		model.addObject("phone", "绑定手机号："+userInfo.getPhone());
		model.addObject("address", "常住地址："+userInfo.getAddress());
		model.addObject("photoImage", "头像："+userInfo.getPhotoImage());
		model.addObject("communityName", "基金所在社区："+userInfo.getCommunityName());
		model.addObject("communityId", "基金所在社区ID："+userInfo.getCommunityId());
		return model;
	}
	
	
	
	/**
	 * 测试会员接口调用2
	 *  manager.vinuxagedcare.com/initParameter/getUserInfoByCartId.vhtml  访问
	 * @return
	 */
	@RequestMapping("getUserInfoByCartId")
	public ModelAndView getUserInfoByCartId(){
		ModelAndView model = new ModelAndView("demo/parameter_index");
//		15210670253   15911102357   13651172908   15201076961  15201076960
//		131125199005021649
//		362423198902104519
		String CardIdOrPhone = "18722044789";
		UserInfoBean userInfo = APIUtils.getUserInfoByCartId(CardIdOrPhone);
		model.addObject("userId", "用户ID："+userInfo.getUserId());
		model.addObject("name", "姓名："+userInfo.getName());
		model.addObject("loginName", "登录名："+userInfo.getLoginName());
		model.addObject("sex", "性别："+userInfo.getSex());
		model.addObject("cartId", "身份证号："+userInfo.getCardId());
		model.addObject("phone", "绑定手机号："+userInfo.getPhone());
		model.addObject("address", "常住地址："+userInfo.getAddress());
		model.addObject("photoImage", "头像："+userInfo.getPhotoImage());
		model.addObject("communityName", "基金所在社区："+userInfo.getCommunityName());
		model.addObject("communityId", "基金所在社区ID："+userInfo.getCommunityId());
		return model;
	}
	
	
	
	/**
	 * 测试会员接口调用3
	 *  manager.vinuxagedcare.com/initParameter/getCommunityInfo.vhtml  访问
	 * @return
	 */
	@RequestMapping("getCommunityInfo")
	public ModelAndView getCommunityInfo(){
		ModelAndView model = new ModelAndView("demo/parameter_index");
		String userId = "201050";
		UserInfoBean userInfo = APIUtils.getCommunityInfo(userId);
		model.addObject("communityName", "基金所在社区名称："+userInfo.getCommunityName());
		model.addObject("communityAddress", "基金所在社区地址："+userInfo.getCommunityAddress());
		model.addObject("population", "基金所在社区人数："+userInfo.getPopulation());
		return model;
	}
	
	
	
	/**
	 * 测试厨房调用接口1
	 *  manager.vinuxagedcare.com/initParameter/getDateInfo.vhtml  访问
	 * @return
	 */
	@RequestMapping("getDateInfo")
	public ModelAndView getDateInfo(){
		ModelAndView model = new ModelAndView("demo/parameter_index");
		List<FoodInfo> list = PensionUtils.getDateInfo();
		model.addObject("list", list);
		return model;
	}
	
	
	/**
	 * 测试厨房调用接口2
	 *  manager.vinuxagedcare.com/initParameter/getFoodInfo.vhtml  访问
	 * @return
	 */
	@RequestMapping("getFoodInfo")
	public ModelAndView getFoodInfo(){
		ModelAndView model = new ModelAndView("demo/parameter_index");
		Integer mediaId = 157;
		Integer pageNo = 1;
		String queryWeek = "星期二";
		
		List<FoodInfo> list = APIUtils.getFoodInfo(mediaId, pageNo, queryWeek);
		model.addObject("list", list);
		return model;
	}
	
	
	/**
	 * 测试基金推送数据接口
	 *  manager.vinuxagedcare.com/initParameter/pushDataToVinuxcare.vhtml  访问
	 * @return
	 */
	@RequestMapping("pushDataToVinuxcare")
	public String pushDataToVinuxcare(){
		Map<String,Object> result = CollectionUtils.newHashMap();
		
		 result = APIUtils.pushDataToVinuxcare("201193","20","8.88","201604271724185803","6","pc_kitchen");
		 
		 String status = result.get("status").toString(); 
		 return status+"";
	}
	

	/**
	 *Method:datelist
	 * <p>Description: 查询数据库显示页面</p>
	 * @author:WFangChao
	 *@return：ModelAndView
	 */
	@SuppressWarnings({ "unchecked", "rawtypes", "resource" })
	@RequestMapping("datelist")
	public ModelAndView datelist(HttpServletRequest request) {
		ModelAndView m = new ModelAndView("common/datelist");
		int allpage=0;
		int rowCount = 0;
		int pageNo=1;
		int pageSize=10;
		Connection conn= null;
		Statement stat = null;
		ResultSet result = null;
		//创建一个用来存放表头的向量
		Vector<String> coln=new Vector<String>();
		//创建一个用来存放数据的向量
		Vector<Vector<String>> data=new Vector<Vector<String>>();
		//创建一个存放所有表名的List
		List<String> nameList=new ArrayList<String>();
		//创建一个可一分页的对象
		Pagination page = new Pagination();
		//从前台页面接收到Sq 
		String sqtext=request.getParameter("selectsq");

		//判断是否为复杂查询,如果是复杂查询直接走SQL查询语句
		String search=request.getParameter("search");

		//从前台页面接收到分页的页数
		String pagen=request.getParameter("pageNo");
		if(StringUtils.isNotBlank(pagen)){
			pageNo=Integer.parseInt(pagen);
		}

		try{
			conn=dataSource.getConnection();
			stat=conn.createStatement();

			//查找出所有数据库的表名
			DatabaseMetaData meta = conn.getMetaData();
			result =meta.getTables(null, null, null,new String[] { "TABLE" });
			while (result.next()) {
				nameList.add((result.getString(3)));
			}

			   //判断是否为复杂查询,直接走SQ语句不带分页
				if(StringUtils.isNotBlank(search)){
					result = stat.executeQuery( sqtext );
					//获取结果集元数据的长度
					ResultSetMetaData rsmd = result.getMetaData();
					int colcount=rsmd.getColumnCount();

					for(int i=1;i<=colcount;i++)
					{//将每个字段的名称添加进向量

						coln.add(rsmd.getColumnName(i));
					}

					while(result.next())
					{
						//为每条记录创建一个向量
						Vector<String> rowv=new Vector<String>();
						for(int i=1;i<=colcount;i++)
						{//将该行记录的各个字段值添加进行向量中
							rowv.add(result.getString(i));
						}
						//将行向量添加进数据向量中
						data.add(rowv);
					}

					page.setList(data);
					m.addObject("colnlist",coln);
					m.addObject("nameList",nameList);
					m.addObject("page",page);
					m.addObject("sqtext",sqtext);
					return m;
				}
				
			//对SQ语句进行处理，加上分页查询
			if(StringUtils.isNotBlank(sqtext)){
				ResultSet    resultcount=null;
				//查询出总共有多少条数据
				//	String countSql = texttt.toUpperCase().s
				String cut = sqtext.substring(sqtext.indexOf("*")+1);
				String contSq=("select 1 "+cut);
				String textcount=("select count(1) as totalCount from ("+contSq+") s");
				if(cut.equals(sqtext)){
					String cutcont=("select count(1) as totalCount from ("+cut+") s");
					resultcount = stat.executeQuery( cutcont );
				}else{
					resultcount = stat.executeQuery( textcount );
				}
				if(resultcount.next()) {
					rowCount=resultcount.getInt("totalCount");
				} 

			}
			
			//查询数据库,并且分页
			if(StringUtils.isNotBlank(sqtext)){
				String text=(sqtext+" limit "+(pageNo-1)*pageSize+","+pageSize);
				// statement用来执行SQL语句
				// 要执行的SQL语句
				result = stat.executeQuery( text );
				//获取结果集元数据的长度
				ResultSetMetaData rsmd = result.getMetaData();
				int colcount=rsmd.getColumnCount();

				for(int i=1;i<=colcount;i++)
				{//将每个字段的名称添加进向量

					coln.add(rsmd.getColumnName(i));
				}

				while(result.next())
				{
					//为每条记录创建一个向量
					Vector<String> rowv=new Vector<String>();
					for(int i=1;i<=colcount;i++)
					{//将该行记录的各个字段值添加进行向量中
						rowv.add(result.getString(i));
					}
					//将行向量添加进数据向量中
					data.add(rowv);
				}

			}
			//把分页数据放入到page对象里面
			page.setPageNo(pageNo);
			page.setPageSize(pageSize);
			page.setList(data);
			page.setTotalCount(rowCount);
		}
		catch (Exception e){
			m.addObject("error","SQL语句格式错误，或者有特殊字符！(注：仅支持查询)");
		}finally{
			try {
				if(result!=null){
					result.close();
				}
				if(stat!=null){
					stat.close();
				}
				if(conn!=null){
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		m.addObject("colnlist",coln);
		m.addObject("page",page);
		m.addObject("sqtext",sqtext);//回显
		m.addObject("nameList",nameList);//所有表
		m.addObject("allpage",allpage);
		return m;
	}
	
	/**
	 * 测试帮手接口
	 *  
	 * @return
	 */
	
	@RequestMapping("getHelperInfo")
	@ResponseBody
	public Map<String,Object> getHelperInfo(){
		String url = "http://vinuxhelper.vinuxpost.com/open/queryHelperProduct.vhtml";
		Map<String,Object> param = new HashMap<>();
		param.put("mediaId", "157");
		VinuxPostMethod post = new VinuxPostMethod(url, param);
		JSONObject result = (JSONObject) post.executeMethod(new String[] { "JSONObject" });
		System.out.println(result.toString());
		Map<String,Object> map = new HashMap<>();
		map.put("result", result.toString());
		return map;
	}
	
}
